<template>
  <main class="container">
    <!-- 功能 -->
    <div class="extra">
      <div class="extra-left">
        <a-button type="primary" @click="open = true">新增类别</a-button>
        <a-button @click="uploadBatchClassification">批量导入</a-button>
      </div>
      <div class="extra-right">
        <a-input-search v-model:value="searchForm.keyword" placeholder="请输入关键词" style="width: 200px" @search="onSearch" />
      </div>
    </div>
    <!-- 表格 -->
    <a-table :columns="columns" :data-source="list" :pagination="false" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'created_at'">{{ formatUnixTimestamp(record.created_at) }}</template>
        <template v-if="column.key == 'updated_at'">{{ formatUnixTimestamp(record.updated_at) }}</template>
        <template v-if="column.key === 'operation'">
          <span class="actions">
            <!-- 编辑 -->
            <FormOutlined @click="updateCategory(record._id)" />
            <!-- 删除 -->
            <a-popconfirm
              title="确定要删除当前类别吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteClassification(record._id)"
            >
              <DeleteOutlined style="margin-left: 16px; color: red" />
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 分页器 -->
    <a-pagination
      v-model:current="curPage"
      v-model:pageSize="pageSize"
      show-size-changer
      :total="total"
      :show-total="(total: number) => `共 ${total} 条数据`"
    />
  </main>
  <!-- 对话框 -->
  <a-modal
    v-model:open="open"
    :title="`${!editId ? '新增' : '编辑'}类别`"
    :footer="null"
    :destroy-on-close="true"
    @cancel="handleCancel"
  >
    <ModalForm @submit="handleSubmit" ref="formRef" />
  </a-modal>
</template>
<script setup lang="ts">
import { reactive, ref, nextTick } from "vue"
import { notification, type TableColumnsType } from "ant-design-vue"
import { FormOutlined, DeleteOutlined } from "@ant-design/icons-vue"
import usePagination from "@/hooks/usePagination"
import { formatUnixTimestamp } from "@/utils"
import { addCaseCategory, deleteCaseCategory, getCaseCategoryInfo, getCaseCategoryList, updateCaseCategory } from "@/api/case"
import ModalForm from "./components/modal-form.vue"

const searchForm = reactive({
  keyword: ""
})
const formRef = ref()
let editId = ref<string>("")
const open = ref<boolean>(false)
let { curPage, total, pageSize, list, updateData, searchQuery, loading } = usePagination(getCaseCategoryList)

const columns: TableColumnsType = [
  { title: "ID", width: 100, dataIndex: "_id", key: "_id", align: "center" },

  {
    title: "分类名称",
    dataIndex: "name",
    key: "name",
    align: "center",
    sorter: { compare: (a: any, b: any) => a.name.localeCompare(b.name) }
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    align: "center",
    sorter: { compare: (a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime() }
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    key: "updated_at",
    align: "center",
    sorter: { compare: (a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime() }
  },
  {
    key: "operation",
    fixed: "right",
    width: 100
  }
]

const onSearch = () => {
  if (!searchForm.keyword) {
    delete searchQuery.name
    updateData()
    return
  }
  searchQuery.name = searchForm.keyword
}

const handleSubmit = async (values: any) => {
  if (!editId.value) {
    // 新增记录
    let res = await addCaseCategory(values)
    res.code == 0 &&
      notification.success({
        message: res.message
      })
  } else {
    let res = await updateCaseCategory(editId.value, values)
    res.code == 0 &&
      notification.success({
        message: res.message
      })
  }
  updateData()
  open.value = false
}
const updateCategory = async (id: string) => {
  editId.value = id
  let res = await getCaseCategoryInfo(id)
  open.value = true
  nextTick(() => {
    //回填数据
    formRef.value.formState.name = res.data!.name
  })
}
const uploadBatchClassification = () => {
  notification.warning({
    message: "功能暂未开放",
    description: "批量上传功能暂不可用，后续将陆续开放！"
  })
}
const handleCancel = () => {
  editId.value = ""
}
const deleteClassification = async (classificationId: string) => {
  let data = await deleteCaseCategory(classificationId)
  if (data.code == 0) {
    notification.success({
      message: data.message
    })
    updateData()
  }
}
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
